package com.jetinno.simple.widget

import android.content.Context
import android.content.res.TypedArray
import android.text.TextUtils
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.widget.RelativeLayout
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.databinding.DataBindingUtil
import com.jetinno.simple.R
import com.jetinno.simple.databinding.ViewHeadbarBinding

class HeadBar @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : RelativeLayout(context, attrs, defStyleAttr) {

    // 使用 DataBinding 绑定布局
    private val mDatabinding: ViewHeadbarBinding = DataBindingUtil.inflate(
        LayoutInflater.from(context),
        R.layout.view_headbar,
        this,
        true
    )

    init {
        attrs?.let {
            val ta: TypedArray = context.obtainStyledAttributes(it, R.styleable.HeadBar)
            // 标题文字
            val titleText = ta.getString(R.styleable.HeadBar_titleText)
            val leftText = ta.getString(R.styleable.HeadBar_leftText)
            val titleTextColor = ta.getColor(
                R.styleable.HeadBar_titleTextColor,
                ContextCompat.getColor(context, R.color.white)
            )
            // 本自定义控件的背景色
            val backgroundColor = ta.getColor(
                R.styleable.HeadBar_backgroundColor,
                ContextCompat.getColor(context, R.color.common_bg_gray2)
            )
            ta.recycle()

            mDatabinding.apply {
                // 设置标题文字
                if (!TextUtils.isEmpty(titleText)) {
                    tvHeadbarTitle.text = titleText
                } else {
                    tvHeadbarTitle.visibility = INVISIBLE
                }
                tvHeadbarTitle.setTextColor(titleTextColor)

                // 设置本自定义控件的背景色
                rlHeadbarRoot.setBackgroundColor(backgroundColor)

                if (!TextUtils.isEmpty(leftText)) {
                    tvHeadbarBack.setText(leftText)
                }
            }
        }
    }

    /**
     * 设置右上角图标
     */
    fun setBackClickListener(listener: View.OnClickListener) {
        mDatabinding.tvHeadbarCancel.setOnClickListener(listener)
    }

    /**
     * 设置左上角图标
     */
    fun setLeftClickListener(listener: View.OnClickListener) {
        mDatabinding.tvHeadbarBack.setOnClickListener(listener)
    }

    /**
     * 获取中间控件
     */
    fun getTitleView(): TextView {
        return mDatabinding.tvHeadbarTitle
    }

    /**
     * 设置中间文字
     */
    fun setTitleText(text: String?) {
        text?.let {
            mDatabinding.tvHeadbarTitle.text = it
        }
    }

    /**
     * 获取右上角图标控件
     */
    fun getBackView(): View {
        return mDatabinding.tvHeadbarCancel
    }

}